package com.buaa.demo.Controller;

import com.buaa.demo.Entity.User;
import com.buaa.demo.Service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.Map;

@CrossOrigin
@RestController
public class LoginController {
    @Autowired
    private UserService userService;

    @PostMapping("/login")

    public Map<String, Object> userLogin(@RequestBody Map<String, String> remap){
        String email = remap.get("email");
        String password = remap.get("password");
        Map<String, Object> map = new HashMap<>();
        StaticPrint.printArgs("User Login", remap);
        try{
            User u = userService.getUserByEmail(email);
            if(u == null){
                map.put("res", false);
                map.put("message", "该邮箱尚未注册，请前往注册！");
            }
            else{
                if(password.equals(u.password)){
                    map.put("res", true);
                    map.put("message", "登陆成功");
                    map.put("user", u);
                }
                else{
                    map.put("res", false);
                    map.put("message", "密码输入错误！");
                }
            }
        } catch(Exception e){
            map.put("res", false);
            map.put("message", "用户登陆失败！");
            e.printStackTrace();
        } finally {
            return map;
        }
    }
}
